<?php

namespace App\Http\Controllers\Home;

use App\Models\Shop;
use App\Support\WechatSilentAuth;
use Carbon\Carbon;
use EasyWeChat\Message\Text;
use EasyWeChat\Message\News;
use App\Models\WechatMenus;
use App\Models\WechatSet;
use App\Models\Member;

class WechatController extends BaseController
{
    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {
        $aid = 1;
        $configArr = [
            'app_id' => '',
            'secret' => '',
        ];
        if ($aid) {
            $wechatSet = new WechatSet();
            $settings = $wechatSet->_getOne(['admin_id' => $aid]);
            config(['wechat.app_id' => $settings['wx_app_id']]);
            config(['wechat.secret' => $settings['wx_app_secret']]);
            config(['wechat.aes_key' => $settings['wx_aes_key']]);

            $configArr = [
                'app_id' => $settings['wx_app_id'],
                'secret' => $settings['wx_app_secret'],
            ];
        }

        $wechat = app('wechat');
        //多公众号相关， 通过参数来调用对应的公众号信息
        $wechat->server->setMessageHandler(function ($message) use ($aid, $configArr) {
            switch ($message['MsgType']) {
                case 'subscribe':  //关注
                    $content = env('VERSION') ? env('WX_WELCOME') : '您好，欢迎关注趣订水微信商户平台';
                    return $content;
                    break;
                case 'event':
                    return $this->dealMsg($message, $aid, $configArr);
                    break;
                case 'text':
//                    if ( $message['FromUserName'] == 'ozmPh0167EjhHcP27HMCr9Ifaeu4') {
//                        $news = new News([
//                            'title'       => 'Hi~ o(*￣▽￣*)ブ',
//                            'description' => '这里是自动回复哦',
//                            'url'         => 'https://www.baidu.com',
//                            'image'       => 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1542879465545&di=4fcee9b38b697ab6b9400920c80fea2e&imgtype=0&src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fimages%2F20180802%2Ffa1563e52ca346cb9bdd1d0d91c6ab31.jpeg',
//                            // ...
//                        ]);
//                        return $news;
//                    }
                    return '';
                    break;
            }
        });

        return $wechat->server->serve();
    }

    public function dealMsg($message, $aid, $config)
    {
        switch ($message['Event']) {
            case 'CLICK' :
                $id = $message['EventKey'];
                $menus = new WechatMenus();
                $res = $menus->_getOneById($id, 'reply_content');
                return new Text(['content' => $res['reply_content']]);
                break;
            case 'subscribe' :
                $eventKey = $message['EventKey'];
                $sid = 0;
                $referMid = 0; // 推广员ID
                $content = env('VERSION') ? env('WX_WELCOME') : '您好，欢迎关注趣订水微信商户平台！';

                if ($eventKey) {
                    $data = explode('_', $eventKey);
                    if (count($data) && filter_var($data[1], FILTER_VALIDATE_URL)) {
                        $params = getUrlParams($data[1]);
                        if (isset($params['sid']) && $params['sid']) {
                            $sid = $params['sid'];
                        }

                        if (strpos($message['EventKey'], 'shop/entrance') !== false) {
                            $data = explode('/', $message['EventKey']);
                            $aid = explode('?', last($data))[0];
                        }
                    }
                    // 带参数二维码
                    if (count($data) && is_json($data[1])) {
                        $params = json_decode($data[1], true);
                        if (isset($params['action'])) {
                            // 受邀注册
                            if ($params['action'] == 'inviteMember') {
                                $sid = $params['shopId'];
                                $shop = (new Shop())->_redisGetOneBySid($sid);
                                $aid = $shop['admin_id'];
                            }

                            // 推广注册
                            if ($params['action'] == 'refer') {
                                $sid = $params['shopId'];
                                $shop = (new Shop())->_redisGetOneBySid($sid);
                                $aid = $shop['admin_id'];
                                $referMid = $params['referMid'];
                            }

                            // 同步码绑定
                            if ($params['action'] == 'bindWx') {
                                $mid = $params['mid'];
                                $content .= $this->bindMemberWx($mid, $message['FromUserName'], $config);

                                return new Text(['content' => $content]);
                            }

                            // 收款信息
                            if($params['action'] == 'receive') {
                                $sid = $params['shopId'];
                                $content .= $this->bindShopReceive($sid, $message['FromUserName']);
                                return new Text(['content' => $content]);
                            }
                        }
                    }
                }

                if ($aid && $sid) {
                    $res = $this->checkUserRegister($aid, $sid, $config, $message['FromUserName'], $referMid);
                    if ($res) {
                        $content = (new Member())->changeMemberDefault($res, $message['FromUserName'], $sid, $referMid);
                    } else {
                        $content = '您绑定店铺失败，请重新扫码！';
                    }
                }
                return new Text(['content' => $content]);
                break;
            case 'SCAN':
                $aid = 0;
                $sid = 0;
                $referMid = 0;

                // 店铺推广注册
                if (filter_var($message['EventKey'], FILTER_VALIDATE_URL)) {
                    // 获取sid
                    $params = getUrlParams($message['EventKey']);
                    if (isset($params['sid']) && $params['sid']) {
                        $sid = $params['sid'];
                    }

                    // 获取aid
                    if (strpos($message['EventKey'], 'shop/entrance') !== false) {
                        $data = explode('/', $message['EventKey']);
                        $aid = explode('?', last($data))[0];
                    }
                }
                // 受邀注册
                if (is_json($message['EventKey'])) {
                    $data = json_decode($message['EventKey'], true);
                    if (isset($data['action'])) {
                        if ($data['action'] == 'inviteMember') {
                            $sid = $data['shopId'];
                            $shop = (new Shop())->_redisGetOneBySid($sid);
                            $aid = $shop['admin_id'];
                        }

                        // 推广注册
                        if ($data['action'] == 'refer') {
                            $sid = $data['shopId'];
                            $shop = (new Shop())->_redisGetOneBySid($sid);
                            $aid = $shop['admin_id'];
                            $referMid = $data['referMid'];
                        }

                        // 同步码绑定
                        if ($data['action'] == 'bindWx') {
                            $mid = $data['mid'];
                            $content = $this->bindMemberWx($mid, $message['FromUserName'], $config);
                            return new Text(['content' => $content]);
                        }

                        // 收款信息
                        if($data['action'] == 'receive') {
                            $sid = $data['shopId'];
                            $content = $this->bindShopReceive($sid, $message['FromUserName']);
                            return new Text(['content' => $content]);
                        }
                    }
                }
                if ($aid && $sid) {
                    $res = $this->checkUserRegister($aid, $sid, $config, $message['FromUserName'], $referMid);
                    if ($res) {
                        $content = (new Member())->changeMemberDefault($res, $message['FromUserName'], $sid, $referMid);
                    } else {
                        $content = '您绑定店铺失败，请重新扫码！';
                    }
                } else {
                    $content = '您绑定店铺失败，请重新扫码';
                }
                return new Text(['content' => $content]);
                break;
        }
    }

    public function checkUserRegister($aid, $sid, $config, $wxOpenId, $referMid)
    {
        $memberModel = new Member();
        $user = $memberModel->_getOne([
            'wx_openid' => $wxOpenId,
            'shop_id' => $sid
        ]);
        if (!$user) {
            $appId = $config['app_id'];
            $appSecret = $config['secret'];
            $silentAuth = new WechatSilentAuth();
            $access_token = $silentAuth->getToken($appId, $appSecret);
            $baseInfo = $silentAuth->getUserInfo($access_token, $wxOpenId, $appId, $appSecret);
            if ($baseInfo && isset($baseInfo['nickname'])) {
                $res = $memberModel->addWxMemberWithWxOpenId($aid, $baseInfo, $sid, $referMid);
                if (!$res) {
                    return false;
                }
            } else {
                return false;
            }
        }
        return true;
    }

    public function bindMemberWx($mid, $openid, $config)
    {
        $silentAuth = new WechatSilentAuth();
        $access_token = $silentAuth->getToken($config['app_id'], $config['secret']);
        $userInfo = $silentAuth->getUserInfo($access_token, $openid, $config['app_id'], $config['secret']);
        if(!$userInfo) {
            $content = '账号关联失败，请再次扫码操作';
        } else {
            $content = (new Member())->bindWxOpenidByMid($mid, $userInfo);
        }

        return $content;
    }

    public function bindShopReceive($sid, $openid)
    {
        $model = new Shop();
        $shopInfo = $model->_getOneById($sid);
        if($shopInfo['wx_openid']) {
            $content = '您已关联微信！';
        } else {
            $res = $model->_update(['id' => $sid], ['wx_openid'=> $openid]);
            if($res) {
                $data = $shopInfo->toArray();
                $data['wx_openid'] = $openid;
                session('shop_info', $data);
                $model->_redisGenerate($sid);
                $model->_redisGetOneBySid($sid);
                $content = '关联微信成功！';
            } else {
                $content = '关联微信失败，请稍后再试！';
            }
        }

        return $content;
    }
}
